package capricornus.components.utils.flick
{
	import capricornus.components.utils.FilterUtils;
	
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import fl.transitions.easing.None;
	
	import flash.display.DisplayObject;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	//明暗闪烁动画
	[Event(name="flickerFinish", type="capricornus.components.utils.flick.FlickerEvent")]
	public class FlickerMotionController extends EventDispatcher
	{
		private static var _dict:Dictionary = new Dictionary();
		
		protected var _target:DisplayObject;
		private var _tween:Tween;
		private var _beginBrightness:int;
		private var _endBrightness:int;
		private var _durationOneTime:Number;
		private var _times:int;
		
		private var _isRemoveOnComplete:Boolean = false;
		
		private var _orginFilters:Array;
		
		public function FlickerMotionController( target:DisplayObject, beginBrightness:int=-40, endBrightness:int=80, durationOneTime:Number=0.25, times:int=10 )
		{
			_target = target;
			_beginBrightness = beginBrightness;
			_endBrightness = endBrightness;
			_durationOneTime = durationOneTime;
			_times = times;
			init();
		}
		
		private function init():void
		{
			_dict[this] = this;
			_orginFilters = _target.filters;
			_tween = new Tween( this, "color", None.easeIn, _beginBrightness, _endBrightness, _durationOneTime, true );
			_tween.addEventListener( TweenEvent.MOTION_FINISH, onMotionFinish, false, 0, true );
			_tween.start();
		}
		
		public function set removeOnComplete( value:Boolean ):void
		{
			_isRemoveOnComplete = value;
		}
		
		public function set color( value:Number ):void
		{
			var arr:Array = FilterUtils.getShineFilter( int(value) );
			if( _orginFilters )
			{
				arr = arr.concat( _orginFilters );
			}
			_target.filters = arr;
		}
		
		private function onMotionFinish( e:TweenEvent ):void
		{
			_times--;
			if( _times > 0 )
			{
				if( _tween.finish==_endBrightness )
				{
					_tween.begin = _endBrightness;
					_tween.finish = _beginBrightness;
				}
				else
				{
					_tween.begin = _beginBrightness;
					_tween.finish = _endBrightness;
				}
				_tween.start();
			}
			else
			{
				destroy();
			}
		}
		
		public function destroy():void
		{
			dispatchEvent( new FlickerEvent( FlickerEvent.FLICKER_FINISH ) );
			if( _isRemoveOnComplete )
			{
				if( _target.parent )
				{
					_target.parent.removeChild( _target );
				}
			}
			delete _dict[this];
			_target.filters = _orginFilters;
			_target = null;
			_tween.removeEventListener( TweenEvent.MOTION_FINISH, onMotionFinish );
			_tween = null;
		}
	}
}













